package com.ruoyi.business.service.impl;

import java.awt.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.business.request.ApiUploadTaskAnnexReq;
import com.ruoyi.business.response.ApiTaskAnnexRes;
import com.ruoyi.business.utils.AddWatermarkUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.TaskAnnexMapper;
import com.ruoyi.business.domain.TaskAnnex;
import com.ruoyi.business.service.ITaskAnnexService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 任务附件Service业务层处理
 *
 * @author Eric
 * @date 2024-03-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TaskAnnexServiceImpl extends ServiceImpl<TaskAnnexMapper, TaskAnnex> implements ITaskAnnexService {

    private final ServerConfig serverConfig;

    @Override
    public Map<String, Object> uploadTaskAnnex(ApiUploadTaskAnnexReq req) {
        MultipartFile file = req.getMultipartFile();
        Map<String, Object> resultMap = Maps.newHashMap();
        String localPath = "";
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            resultMap.put("url", url);
            resultMap.put("fileName", fileName);
            resultMap.put("newFileName", FileUtils.getName(fileName));
            resultMap.put("originalFilename", file.getOriginalFilename());
            String aFile = StrUtil.sub(fileName, Constants.RESOURCE_PREFIX.length(), fileName.length());
            localPath = RuoYiConfig.getProfile() + aFile;
        } catch (Exception e) {
            throw new ServiceException("上传任务附件失败，原因：" + e.getMessage());
        }

        String lon = StrUtil.format("经  度：{}", Convert.toStr(req.getLon()));
        String lat = StrUtil.format("纬  度：{}", Convert.toStr(req.getLat()));
        String address = StrUtil.format("地  址：{}", req.getAddress());
        String pointName = StrUtil.format("点位名称：{}", req.getTaskPointName());
        String nowDate = StrUtil.format("时  间：{}", DateUtil.now());
        if (StrUtil.equals(req.getType(), "0")) {
            List<String> contentList = Lists.newArrayList();
            contentList.add(lon);
            contentList.add(lat);
            contentList.add(address);
            contentList.add(pointName);
            contentList.add(nowDate);
            Color color = Color.WHITE;//waterMarkProperties.getPhoto().getColor();
            AddWatermarkUtil.waterPress(localPath, color, 40, contentList);
        } else if (StrUtil.equals(req.getType(), "1")) {

        }
        TaskAnnex taskAnnex = new TaskAnnex();
        taskAnnex.setTaskId(req.getTaskId());
        taskAnnex.setTaskPointId(req.getTaskPointId());
        taskAnnex.setUserId(SecurityUtils.getUserId());
        taskAnnex.setFileUrl(MapUtil.getStr(resultMap, "fileName"));
        taskAnnex.setType(req.getType());
        taskAnnex.setCreateBy(SecurityUtils.getUsername());
        taskAnnex.setCreateTime(new Date());
        if (this.save(taskAnnex)) {
            resultMap.put("annexId", taskAnnex.getId());
            return resultMap;
        } else {
            throw new ServiceException("上传调研任务文件失败。");
        }
    }

    @Override
    public Boolean deleteTaskAnnex(Long id) {
        return removeById(id);
    }

    @Override
    public List<ApiTaskAnnexRes> listTaskAnnex(Long taskPointId) {
        List<TaskAnnex> list = this.list(Wrappers.lambdaQuery(TaskAnnex.class)
                .eq(TaskAnnex::getUserId, SecurityUtils.getUserId())
                .eq(TaskAnnex::getTaskPointId, taskPointId));
        List<ApiTaskAnnexRes> resultList = Lists.newArrayListWithCapacity(list.size());
        if (CollUtil.isNotEmpty(list)) {
            for (TaskAnnex taskAnnex : list) {
                ApiTaskAnnexRes res = ApiTaskAnnexRes.builder()
                        .annexId(taskAnnex.getId())
                        .fileUrl(serverConfig.getUrl() + taskAnnex.getFileUrl())
                        .type(taskAnnex.getType())
                        .build();
                resultList.add(res);
            }
        }
        return resultList;
    }
}
